import axios from "axios";
import Local from "tools-utils/storage";
import { ElMessageBox } from "element-plus";
import { router } from "@/router/index";

// 重新登录弹窗
let reLoginBox = null;

// 配置请求头
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
axios.defaults.headers["clientid"] = import.meta.env.VITE_APP_CLIENT_ID;

// 配置新建一个 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL + import.meta.env.VITE_API_PREFIX,
  timeout: import.meta.env.VITE_API_TIMEOUT,
  // 默认所有请求都需要携带 token
  headers: {
    isToken: true, // 默认所有接口强制携带 token
    "x-http-ext-version": "1.0.0",
    "x-http-ext-userRequestSide": 1,
    "x-http-ext-request-platform": 1,
  },
});

// request拦截器
service.interceptors.request.use(
  config => {
    let token = Local.get("token");
    // 请求头添加 token
    if (config.headers.isToken && token) {
      config.headers["x-http-ext-token"] = Local.get("token");
    }

    return config;
  },
  error => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || "200";
    // 获取错误信息
    const msg = res.data.message || "系统未知错误，请反馈给管理员";
    // 获取响应信息
    const data = res.data || {};

    // 处理登录失效
    if (code === "100000007") {
      // 清除浏览器全部临时缓存
      Local.clear();
      // 禁止弹窗多次
      if (reLoginBox) return;
      // 标记重新登录弹窗
      reLoginBox = true;
      // 跳转至登录页
      handleGoToLogin();
      // 弹窗提示，账号认证已过期，请重新登录
      ElMessageBox.alert("账号认证已过期，请重新登录", "提示", { type: "warning" }).finally(() => {
        // 重置重新登录弹窗
        reLoginBox = null;
      });
      return Promise.reject(new Error("无效的会话，或者会话已过期，请重新登录。"));
    }

    // 错误处理
    if (code != 200) {
      $msg.error(msg);
      return Promise.reject(new Error(msg));
    }

    // 请求成功，返回响应体
    return data;
  },
  error => {
    console.log("err" + error);
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    $msg.error(message, { duration: 5 * 1000 });
    return Promise.reject(error);
  }
);

// 跳转到登录页
const handleGoToLogin = () => {
  nextTick(() => {
    if (/^\/.+/.test(router.currentRoute.value.path)) {
      const curPath = router.currentRoute.value.path;
      const curQuery = router.currentRoute.value.query;
      const curParams = router.currentRoute.value.params;
      router.push({
        path: "/login",
        query: {
          redirect: curPath,
          params: JSON.stringify(curQuery ? curQuery : curParams),
        },
      });
    } else {
      router.push({ path: "/login" });
    }
  });
};

// 导出 axios 实例
export default service;
